package logic

import (
	"context"

	"github.com/eeppee_admin/clouddisk/service/internal/svc"
	"github.com/eeppee_admin/clouddisk/service/internal/types"
	"errors"
	"github.com/eeppee_admin/clouddisk/service/model"
	"github.com/eeppee_admin/clouddisk/service/helper"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserFolderCreateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserFolderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFolderCreateLogic {
	return &UserFolderCreateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserFolderCreateLogic) UserFolderCreate(req *types.UserFolderCreateRequest, userIdentity string) (resp *types.UserFolderCreateResponse, err error) {
    // 检查文件夹名称是否已存在
    cnt, err := l.svcCtx.Engine.
        Where("name = ? AND parent_id = ?", req.Name, req.ParentId).
        Count(new(model.UserStore))
    if err != nil {
        logx.Error(err)
        return nil, err
    }
    if cnt > 0 {
        return nil, errors.New("文件夹名称已存在")
    }

    // 创建新文件夹记录
    newFolder := &model.UserStore{
        Name:         req.Name,
        ParentId:     req.ParentId,
        UserIdentity: userIdentity, // 假设这里有一个默认的用户身份
        Identity:    helper.UUID(),
    }

    // 插入新文件夹记录到数据库
    _, err = l.svcCtx.Engine.Insert(newFolder)
    if err != nil {
        logx.Error(err)
        return nil, err
    }

    // 返回成功响应
    resp = &types.UserFolderCreateResponse{
        Identity: newFolder.Identity,
    }
    return resp, nil
}